package io.read;

import io.FileDemo;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class FileReaderDemo {
    public static void main(String[] args) throws IOException {
        String p = FileDemo.getJavaFilePath(FileReaderDemo.class, "") + "/../1.txt";
        //System.out.println(read(p));
        System.out.println(read(new char[20], p));
    }

    /**
     * 读取多个字符到缓冲数组里
     * @param cbuf
     * @param filePath
     * @return
     */
    public static String read(char cbuf[], String filePath) {
        FileReader fr = null;
        StringBuffer sb = new StringBuffer();
        int ch = 0;
        int n = 0;
        try {
            fr = new FileReader(filePath);
            while ((ch = fr.read(cbuf)) != -1) {
                System.out.println("读取的字符个数:" + ch);
                sb.append(cbuf, 0, ch);
                n += ch;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("字符总数:" + n);
        return sb.toString();
    }

    /**
     * 一次读一个字符
     *
     * @param filePath
     */
    public static String read(String filePath) {
        FileReader fr = null;
        StringBuffer sb = new StringBuffer();
        try {
            fr = new FileReader(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int ch = 0;
        int n = 0;
        try {
            while ((ch = fr.read()) != -1) {
                sb.append((char) ch);
                n++;
            }
        } catch (IOException e) {
        }
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("字符总数:" + n);
        return sb.toString();
    }
}